<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋对战房间</title>
    <style>
        /* 全局样式重置与基础设置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f0f2f5;
            background-image: url("data:image/svg+xml,%3Csvg width='100' height='100' viewBox='0 0 100 100' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M11 18c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm48 25c3.866 0 7-3.134 7-7s-3.134-7-7-7-7 3.134-7 7 3.134 7 7 7zm-43-7c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm63 31c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM34 90c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zm56-76c1.657 0 3-1.343 3-3s-1.343-3-3-3-3 1.343-3 3 1.343 3 3 3zM12 86c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm28-65c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm23-11c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-6 60c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm29 22c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zM32 63c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm57-13c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm-9-21c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM60 91c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM35 41c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2zM12 60c1.105 0 2-.895 2-2s-.895-2-2-2-2 .895-2 2 .895 2 2 2z' fill='%239C92AC' fill-opacity='0.05' fill-rule='evenodd'/%3E%3C/svg%3E");
            min-height: 100vh;
            padding-bottom: 50px;
        }

        /* 导航栏样式 */
        .nav {
            background-color: #2c3e50;
            color: #ecf0f1;
            text-align: center;
            padding: 15px 0;
            font-size: 1.5rem;
            font-weight: bold;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        /* 主容器样式 */
        .container {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            gap: 30px;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }

        /* 棋盘区域样式 */
        #chess_area {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 15px;
        }

        #chess {
            border: 8px solid #8B4513;
            border-radius: 5px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            background-color: #F5DEB3;
            transition: transform 0.3s ease;
        }

        #chess:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
        }

        #screen {
            background-color: rgba(255, 255, 255, 0.8);
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 1.1rem;
            font-weight: 500;
            color: #2c3e50;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            min-width: 200px;
            text-align: center;
        }

        /* 聊天区域样式 */
        #chat_area {
            width: 350px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        #chat_show {
            height: 400px;
            padding: 15px;
            overflow-y: auto;
            flex-grow: 1;
            background-color: #f9f9f9;
        }

        #chat_show p {
            margin-bottom: 10px;
            max-width: 80%;
            padding: 8px 12px;
            border-radius: 18px;
            line-height: 1.4;
            word-wrap: break-word;
        }

        #self_msg {
            background-color: #dcf8c6;
            margin-left: auto;
            text-align: right;
        }

        #peer_msg {
            background-color: #ffffff;
            border: 1px solid #e0e0e0;
            margin-right: auto;
        }

        #msg_show {
            display: flex;
            padding: 10px;
            border-top: 1px solid #eee;
        }

        #chat_input {
            flex-grow: 1;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
            font-size: 1rem;
            transition: border-color 0.3s;
        }

        #chat_input:focus {
            border-color: #6495ed;
        }

        #chat_button {
            margin-left: 10px;
            padding: 0 20px;
            background-color: #6495ed;
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s, transform 0.2s;
        }

        #chat_button:hover {
            background-color: #4169e1;
            transform: scale(1.05);
        }

        #chat_button:active {
            transform: scale(0.98);
        }

        /* 返回大厅按钮样式 */
        #chess_area div[onclick] {
            margin-top: 15px;
            padding: 8px 20px;
            background-color: #e74c3c;
            color: white;
            border-radius: 20px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.3s;
        }

        #chess_area div[onclick]:hover {
            background-color: #c0392b;
        }

        /* 响应式设计 */
        @media (max-width: 850px) {
            .container {
                flex-direction: column;
                align-items: center;
            }

            #chat_area {
                width: 100%;
                max-width: 450px;
            }
        }

        @media (max-width: 500px) {
            #chess {
                width: 100%;
                height: auto;
                max-width: 300px;
                max-height: 300px;
            }

            .nav {
                font-size: 1.2rem;
                padding: 12px 0;
            }

            #chat_area {
                width: 90%;
            }
        }
    </style>
</head>

<body>
    <div class="nav">网络五子棋对战游戏</div>
    <div class="container">
        <div id="chess_area">
            <!-- 棋盘区域, 需要基于 canvas 进行实现 -->
            <canvas id="chess" width="450px" height="450px"></canvas>
            <!-- 显示区域 -->
            <div id="screen"> 等待玩家连接中... </div>
        </div>
        <div id="chat_area">
            <div id="chat_show">
                <p id="self_msg">你好！</p>
                <p id="peer_msg">你好！</p>
            </div>
            <div id="msg_show">
                <input type="text" id="chat_input" placeholder="输入消息...">
                <button id="chat_button">发送</button>
            </div>
        </div>
    </div>
    <script>
        // 原有JavaScript代码保持不变
        let chessBoard = [];
        let BOARD_ROW_AND_COL = 15;
        let chess = document.getElementById('chess');
        let context = chess.getContext('2d');//获取chess控件的2d画布

        var ws_url = "ws://" + location.host + "/room";
        var ws_hdl = new WebSocket(ws_url);

        var room_info = null;//用于保存房间信息 
        var is_me;

        function initGame() {
            initBoard();
            context.strokeStyle = "#5D4037"; // 加深棋盘线条颜色，更清晰
            // 背景图片 - 可以考虑更换为更贴合棋盘的背景
            let logo = new Image();
            logo.src = "image/sky.jpeg";
            logo.onload = function () {
                // 绘制图片
                context.drawImage(logo, 0, 0, 450, 450);
                // 绘制棋盘
                drawChessBoard();
            }
        }
        function initBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                chessBoard[i] = [];
                for (let j = 0; j < BOARD_ROW_AND_COL; j++) {
                    chessBoard[i][j] = 0;
                }
            }
        }
        // 绘制棋盘网格线
        function drawChessBoard() {
            for (let i = 0; i < BOARD_ROW_AND_COL; i++) {
                context.moveTo(15 + i * 30, 15);
                context.lineTo(15 + i * 30, 430); //横向的线条
                context.stroke();
                context.moveTo(15, 15 + i * 30);
                context.lineTo(435, 15 + i * 30); //纵向的线条
                context.stroke();
            }
            // 绘制棋盘上的五个关键点
            drawDot(3, 3);
            drawDot(3, 11);
            drawDot(7, 7);
            drawDot(11, 3);
            drawDot(11, 11);
        }

        // 绘制棋盘上的天元和星位
        function drawDot(x, y) {
            context.beginPath();
            context.arc(15 + x * 30, 15 + y * 30, 5, 0, 2 * Math.PI);
            context.closePath();
            context.fillStyle = "#000";
            context.fill();
        }

        //绘制棋子
        function oneStep(i, j, isWhite) {
            if (i < 0 || j < 0) return;
            context.beginPath();
            context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
            context.closePath();
            var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
            // 区分黑白子
            if (!isWhite) {
                gradient.addColorStop(0, "#0A0A0A");
                gradient.addColorStop(1, "#636766");
            } else {
                gradient.addColorStop(0, "#D1D1D1");
                gradient.addColorStop(1, "#F9F9F9");
            }
            context.fillStyle = gradient;
            context.fill();
            // 棋子阴影效果，增强立体感
            context.shadowColor = "rgba(0, 0, 0, 0.3)";
            context.shadowBlur = 5;
            context.shadowOffsetX = 2;
            context.shadowOffsetY = 2;
        }
        //棋盘区域的点击事件
        chess.onclick = function (e) {
            //  1. 获取下棋位置，判断当前下棋操作是否正常
            //      1. 当前是否轮到自己走棋了
            //      2. 当前位置是否已经被占用
            //  2. 向服务器发送走棋请求
            if (!is_me) {
                // 替换alert为更友好的提示方式
                document.getElementById('screen').textContent = "⏳ 等待对方走棋....";
                return;
            }
            let x = e.offsetX;
            let y = e.offsetY;
            // 注意, 横坐标是列, 纵坐标是行
            // 这里是为了让点击操作能够对应到网格线上
            let col = Math.floor(x / 30);
            let row = Math.floor(y / 30);
            if (chessBoard[row][col] != 0) {
                document.getElementById('screen').textContent = "❌ 当前位置已有棋子！";
                return;
            }
            //向服务器发送走棋请求，收到响应后，再绘制棋子
            send_chess(row, col);
        }
        function send_chess(r, c) {
            var chess_info = {
                optype: "put_chess",
                room_id: room_info.room_id,
                uid: room_info.uid,
                row: r,
                col: c
            };
            ws_hdl.send(JSON.stringify(chess_info));
            console.log("click:" + JSON.stringify(chess_info));
        }

        window.onbeforeunload = function () {
            ws_hdl.close();
        }
        ws_hdl.onopen = function () {
            console.log("房间长连接建立成功");
        }
        ws_hdl.onclose = function () {
            alert("房间长链接断开")
            console.log("房间长连接断开");
        }
        ws_hdl.onerror = function () {
            console.log("房间长连接出错");
        }
        function set_screen(me) {
            var screen_div = document.getElementById("screen");
            if (me) {
                screen_div.innerHTML = "✅ 轮到己方走棋...";
            } else {
                screen_div.innerHTML = "⏳ 轮到对方走棋...";
            }
        }
        ws_hdl.onmessage = function (evt) {
            //alert(evt.data);
            //1. 在收到room_ready之后进行房间的初始化
            //  1. 将房间信息保存起来
            var info = JSON.parse(evt.data);
            console.log(JSON.stringify(info));
            if (info.optype == "room_ready") {
                room_info = info;
                is_me = room_info.uid == room_info.white_id ? true : false;
                set_screen(is_me);
                initGame();
            } else if (info.optype == "put_chess") {
                console.log("put_chess" + evt.data);
                //2. 走棋操作
                //  3. 收到走棋消息，进行棋子绘制
                if (info.result == false) {
                    document.getElementById('screen').textContent = "❌ " + info.reason;
                    return;
                }
                //当前走棋的用户id，与我自己的用户id相同，就是我自己走棋，走棋之后，就轮到对方了
                is_me = info.uid == room_info.uid ? false : true;
                //绘制棋子的颜色，应该根据当前下棋角色的颜色确定
                isWhite = info.uid == room_info.white_id ? true : false;
                //绘制棋子
                if (info.row != -1 && info.col != -1) {
                    oneStep(info.col, info.row, isWhite);
                    //设置棋盘信息
                    chessBoard[info.row][info.col] = 1;
                }
                //是否有胜利者
                if (info.winner == 0) {
                    set_screen(is_me);
                    return;
                }
                var screen_div = document.getElementById("screen");
                if (room_info.uid == info.winner) {
                    screen_div.innerHTML = "🎉 " + info.reason;
                } else {
                    screen_div.innerHTML = "💔 很遗憾，你输了";
                }

                var chess_area_div = document.getElementById("chess_area");
                var button_div = document.createElement("div");
                button_div.innerHTML = "返回大厅";
                button_div.onclick = function () {
                    ws_hdl.close();
                    location.replace("/game_hall.html");
                }
                chess_area_div.appendChild(button_div);
            } else if (info.optype == "chat") {
                //收到一条消息，判断result，如果为true则渲染一条消息到显示框中
                if (info.result == false) {
                    alert(info.reason);
                    return;
                }
                var msg_div = document.createElement("p");
                msg_div.innerHTML = info.message;
                if (info.uid == room_info.uid) {
                    msg_div.setAttribute("id", "self_msg");
                } else {
                    msg_div.setAttribute("id", "peer_msg");
                }
                var msg_show_div = document.getElementById("chat_show");
                msg_show_div.appendChild(msg_div);
                // 自动滚动到底部
                msg_show_div.scrollTop = msg_show_div.scrollHeight;
                document.getElementById("chat_input").value = "";
            }
        }
        //3. 聊天动作
        //  1. 捕捉聊天输入框消息
        //  2. 给发送按钮添加点击事件，点击俺就的时候，获取到输入框消息，发送给服务器
        var cb_div = document.getElementById("chat_button");
        cb_div.onclick = function () {
            var input = document.getElementById("chat_input");
            var message = input.value.trim();
            if (!message) return; // 空消息不发送

            var send_msg = {
                optype: "chat",
                room_id: room_info.room_id,
                uid: room_info.uid,
                message: message
            };
            ws_hdl.send(JSON.stringify(send_msg));
        }

        // 支持回车键发送消息
        document.getElementById("chat_input").addEventListener("keypress", function (e) {
            if (e.key === "Enter") {
                document.getElementById("chat_button").click();
            }
        });
    </script>
</body>

</html>